<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Register extends CI_Controller {

	public function __construct(){
		parent::__construct();
		$this->load->model('model_user');
	}

	public function register_student()
	{
		$data['title'] = "Sinh Viên Đăng Ký";
		$data['subview'] = 'users/register_student';
		$this->load->view('main', $data);
	}

	public function register_employer()
	{
		$data['title'] = "Doanh Nghiệp Đăng Ký";
		$data['subview'] = 'users/register_employer';
		$this->load->view('main', $data);
	}
	var $test =1;

	public function student()
	{
        $this->form_validation->set_rules('email', 'Email', 'valid_email|trim|required|min_length[10]|xss_clean|is_unique[dang_nhap.email_dn]');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|md5');
        $this->form_validation->set_rules('cpassword', 'Password Confirmation', 'trim|required|min_length[6]|matches[password]');
        // $this->form_validation->set_rules('mssv', 'Student ID', 'trim|required|min_length[7]|numeric|is_unique[thongtin_sv.mssv]');
        $this->form_validation->set_rules('ten', 'First Name', 'trim|required');
        $this->form_validation->set_rules('ho', 'Last Name', 'trim|required');
        $this->form_validation->set_rules('phone', 'Phone Number', 'trim|required|min_length[7]|numeric');
        $this->form_validation->set_rules('birthday', 'Birthday', 'required|callback_check_age');

        $this->form_validation->set_message('is_unique', 'Dữ liệu này đã tồn tại trong hệ thống!');
        if($this->form_validation->run() == FALSE){
            $data['title'] = "Sinh Viên Đăng Ký";
			$data['subview'] = 'users/register_student';
			$this->load->view('main', $data);
        }else {
			if(!$this->session->flashdata('message')) {
				echo "<script type='text/javascript'>history.back(alert('Please select your avatar'));</script>";
			}else {
				// generate a random key
				$key = md5(uniqid());

				// send an email to the user to active account
				$config = array(
					'protocol' => 'smtp',
			        'smtp_host' => 'ssl://smtp.googlemail.com',
			        'smtp_port' => 465,
			        'smtp_user' => 'uit.ghost@gmail.com',
			        'smtp_pass' => 'p4ssw0rd3592',
			        'mailtype'  => 'html', 
			        'charset' => 'utf-8',
			        'wordwrap' => TRUE
			    );
				$this->load->library('email', $config);
				$this->email->set_newline("\r\n");
				
				$this->email->from('uit.ghost@gmail.com', 'UIT_GHOST');
				$this->email->to($this->input->post('email'));
				$this->email->subject('Active your account!');

				$message = "<p>Thank you for signing up ! </p>";
				$message .= "<p><a href='".base_url()."register/active/$key'>Click here</a> to active your account!</p>";
				
				$this->email->message($message);

				if($this->model_user->add_student()) {
					$email = $this->input->post('email');
					$id = $this->model_user->get_id($email)['id_dn'];
					$this->session->set_userdata('id', $this->model_user->get_id($email)['id_dn']);
					$this->session->set_userdata('level',$this->model_user->get_id($email)['level']);
					$this->session->set_userdata('ten_sv', $this->input->post('ten'));
					if($this->model_user->add_student_info($id)) {
						if ($this->email->send()){
							header('Content-Type: text/html; charset=utf-8');  
							echo "<script type='text/javascript'> 
							 	 alert('Đăng ký thành công! Bạn vui lòng kiểm tra email để kích hoạt tài khoản!');
								 window.location.href ='".base_url()."trang-chu';
								 </script>";
						}else {
							// echo $this->email->print_debugger();
							header('Content-Type: text/html; charset=utf-8');  
							echo "<script type='text/javascript'> 
							 	 alert('Không thể gửi email!');
								 window.location.href = '".base_url()."register-student';
								 </script>";
						}
					}else {
						header('Content-Type: text/html; charset=utf-8');
						echo "<script type='text/javascript'> 
						 	 alert('Đã xảy ra lỗi trong quá trình cập nhật CSDL! Bạn vui lòng thực hiện lại sau!');
							 window.location.href = '".base_url()."register-student';
							 </script>";
					}
				}else {
					header('Content-Type: text/html; charset=utf-8');
					echo "<script type='text/javascript'> 
						 	 alert('Đã xảy ra lỗi trong quá trình cập nhật CSDL! Bạn vui lòng thực hiện lại sau!');
							 window.location.href = '".base_url()."register-student';
							 </script>";
				}

			}
        }
	}

	public function check_age() {
		$age = date_diff(date_create($this->input->post('birthday')), date_create('now'))->y;
		if($age >= 18) return TRUE;
			else{
				$this->form_validation->set_message('check_age', 'Bạn chưa đủ tuổi');
				return FALSE;
			}
	}

	public function doupload() {
		$valid_formats = array("jpg", "png", "gif", "bmp", "JPG", "PNG", "GIF", "BMP");
		if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
		{
			$name = $_FILES['photoimg']['name'];
			$size = $_FILES['photoimg']['size'];
			if(strlen($name))
				{
					if(file_exists("upload/".$name)) echo "Hình này đã tồn tại. Xin vui lòng chọn hình khác!";
					else
					{
						list($txt, $ext) = explode(".", $name);
						if(in_array($ext,$valid_formats))
						{
						if($size<(1024*1024))
							{
								$tmp = $_FILES['photoimg']['tmp_name'];
								if(move_uploaded_file($tmp,'upload/'.$name))
									{								
										echo "<img src='".base_url()."upload/".$name."'  class='preview'>";
										$this->session->set_flashdata('message', base_url().'upload/'.$name);
									}
								else
									echo "Lỗi";
							}
							else
							echo "Kích thước tối đa là 1MB";					
							}
							else
							echo "Không đúng định dạng file!";	
					}
				}
				
			else
				echo "Xin vui lòng chọn hình...!";
			exit;
		}
	}

	public function active($key) {
		$id = $this->session->userdata('id');
		if($this->model_user->active($id)) {
			$this->session->set_userdata('active',$this->model_user->active($id));
			$url = base_url().'trang-chu';
			header("Location: $url");
			exit();
		}else {
			echo "<script type='text/javascript'> 
						 	 alert('Không thể kích hoạt tài khoản của bạn!');
							 window.location.href = '".base_url()."trang-chu';
							 </script>";
		}
	}
	public function employer() {
		$this->form_validation->set_rules('email', 'Email', 'valid_email|trim|required|min_length[8]|xss_clean|is_unique[dang_nhap.email_dn]');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|md5');
        $this->form_validation->set_rules('cpassword', 'Password Confirmation', 'trim|required|min_length[6]|matches[password]');
        $this->form_validation->set_rules('ten', 'Ten Cong Ty', 'trim|required');
        $this->form_validation->set_rules('lh', 'Nguoi lien he', 'trim|required');
        $this->form_validation->set_rules('phone', 'Phone Number', 'trim|required|min_length[7]|numeric');
        $this->form_validation->set_rules('email_lh', 'Email lien he', 'valid_email|trim|required|min_length[8]|xss_clean');

        $this->form_validation->set_message('is_unique', 'Email này đã tồn tại!');
        if($this->form_validation->run() == FALSE){
            $data['title'] = "Doanh Nghiệp Đăng Ký";
			$data['subview'] = 'users/register_employer';
			$this->load->view('main', $data);
        }else {
        	if(!$this->session->flashdata('message')) {
				echo "<script type='text/javascript'>history.back(alert('Please select your avatar'));</script>";
			}else {
				// generate a random key
				$key = md5(uniqid());

				// send an email to the user to active account
				$config = array(
					'protocol' => 'smtp',
			        'smtp_host' => 'ssl://smtp.googlemail.com',
			        'smtp_port' => 465,
			        'smtp_user' => 'uit.ghost@gmail.com',
			        'smtp_pass' => 'p4ssw0rd3592',
			        'mailtype'  => 'html', 
			        'charset' => 'utf-8',
			        'wordwrap' => TRUE
			    );
				$this->load->library('email', $config);
				$this->email->set_newline("\r\n");
				
				$this->email->from('uit.ghost@gmail.com', 'UIT_GHOST');
				$this->email->to($this->input->post('email'));
				$this->email->subject('Active your account!');

				$message = "<p>Thank you for signing up ! </p>";
				$message .= "<p><a href='".base_url()."register/active/$key'>Click here</a> to active your account!</p>";
				
				$this->email->message($message);

				if($this->model_user->add_employer()) {
					$email = $this->input->post('email');
					$id = $this->model_user->get_id($email)['id_dn'];
					$this->session->set_userdata('id', $id);
					$this->session->set_userdata('level',$this->model_user->get_id($email)['level']);
					$this->session->set_userdata('ten_dn', $this->input->post('ten'));
					if($this->model_user->add_employer_info($id)) {
						if ($this->email->send()){
						echo "<script type='text/javascript'> 
						 	 alert('Register success! Please check your email to active your account!');
							 window.location.href ='".base_url()."trang-chu';
							 </script>";
						}else {
							echo "<script type='text/javascript'> 
							 	 alert('Can not send email!');
								 window.location.href = '".base_url()."register-employer';
								 </script>";
						}
					}else {
						echo "<script type='text/javascript'> 
						 	 alert('Problem with database!');
							 window.location.href = '".base_url()."register-employer';
							 </script>";
					}
				}else {
					echo "<script type='text/javascript'> 
						 	 alert('Problem with database!');
							 window.location.href = '".base_url()."register-employer';
							 </script>";
				}
			}
        }
	}

}
